//
//  GoogleDataWrapper.m
//  Fuel Log 4
//
//  Created by Olaf on 25.05.10.
//  Copyright 2010 olafgreck. All rights reserved.
//

#import "GoogleDataWrapper.h"
#import "PrefsV2ViewController.h"
#import "SFHFKeychainUtils.h"

@implementation GoogleDataWrapper
@synthesize userNameString, passWordString;

- (id)init 
{
    if (self = [super init])
    {
	}
	NSError * error;
	self.userNameString = [[SFHFKeychainUtils  getPasswordForUsername:_username 
												  andServiceName:_onlineServiceNameGoogleDocs 
														   error:&error] retain];
	if ([userNameString length] > 0 && error == 0) {
		self.passWordString =[[SFHFKeychainUtils  getPasswordForUsername:_password 
													 andServiceName:_onlineServiceNameGoogleDocs 
															  error:&error] retain];
	}
	return self;
}

#pragma mark -
- (GDataServiceGoogleDocs *)docsService {	
	if (!docService) {
		docService = [[GDataServiceGoogleDocs alloc] init];		
		[docService setUserAgent:_UserAgentIdString];
		[docService setShouldCacheDatedData:NO];
		[docService setShouldServiceFeedsIgnoreUnknowns:YES];		
		[docService setServiceShouldFollowNextLinks:YES];
	}
	
	// username/password may change
		NSError *error = nil;
	self.userNameString = [SFHFKeychainUtils  getPasswordForUsername:_username 
												  andServiceName:_onlineServiceNameGoogleDocs 
														   error:&error] ;
	if ([userNameString length] > 0 && error == 0) {
		self.passWordString =[SFHFKeychainUtils  getPasswordForUsername:_password 
													 andServiceName:_onlineServiceNameGoogleDocs 
															  error:&error] ;
	}
	else debug(@"Error: &@", &error);

	
	[docService setUserCredentialsWithUsername:userNameString password:passWordString];
	return docService;
}

- (void)uploadBlankSpreadsheetToDocListFeed:(GDataFeedDocList *)docListFeed
{
	NSString *colNames = @"col1,col2,col3";
	NSData *data = [colNames dataUsingEncoding:NSUTF8StringEncoding];
	
	GDataEntrySpreadsheetDoc *newEntry = [GDataEntrySpreadsheetDoc
										  documentEntry];
	[newEntry setTitleWithString:@"New Empty Spreadsheet"];
	[newEntry setUploadData:data];
	[newEntry setUploadMIMEType:@"text/csv"];
	[newEntry setUploadSlug:@"New Empty Spreadsheet.csv"];
	
	NSURL *postURL = [[docListFeed postLink] URL];
	
	GDataServiceGoogleDocs *service = [self docsService];
	[service fetchEntryByInsertingEntry:newEntry
							 forFeedURL:postURL
							   delegate:self
					  didFinishSelector:@selector
	 (createSpreadsheetTicket:finishedWithEntry:error:)];
	
}

- (void)createSpreadsheetTicket:(GDataServiceTicket *)ticket
              finishedWithEntry:(GDataEntrySpreadsheetDoc *)entry
                          error:(NSError *)error {
	NSLog(@"new spreadsheet entry: %@ \nerror:%@", entry, error);
 
}


@end
